<?php

namespace Frieza\Modules\CommunityMcn\Controllers;

use App\Http\Controllers\Controller;
use App\Pockets\GridDataModel as pGridDataModel;
use Doraemon\tools\PointConfig;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Grid;
use Encore\Admin\Layout\Content;
use Doraemon\service\CommunityMcn\GoodsRecommender as sGoodsRecommender;
use Illuminate\Http\Request;
use Doraemon\model\CommunityMcn\GoodsRecommenderReward;
use Doraemon\model\CommunityMcn\GoodsRecommender as mGoodsRecommender;
use Doraemon\tools\IdParse;
use Doraemon\cache\Queue;

class JoinListController extends Controller{

    public function index(Request $request,Content $content, $id = 0){
        $params = $request->all();
        $sort = $params['_sort'];
        $data = sGoodsRecommender::getActNotes($id,$sort);
        $recommenderInfo = sGoodsRecommender::getDetail($id,false);
        $data = array_values($data);
        $gridModel = new pGridDataModel($data);
        $listGrid = Admin::grid($gridModel, function (Grid $grid) use ($recommenderInfo){
            $grid->disablePagination();
            $grid->disableExport();
            $grid->disableRowSelector();
            $grid->disableFilter();
            $grid->disableCreateButton();
            $grid->column('note_id','内容id')->display(function () {
                return "<a href='/admin/photo/photoList/index?&note_id={$this->note_id}' target='_blank' >$this->note_id</a>";
            });
            $grid->column('like', '点赞')->sortable();
            $grid->column('favorite', '收藏')->sortable();
            $grid->column('comments', '评论')->sortable();
            $grid->column('wiki', 'wiki访问')->sortable();
            $grid->column('interactive', '总交互数')->sortable();
            $grid->column('nick', '作者昵称');
            $grid->column('uid', '作者uid');
            $grid->column('fans', '作者粉丝数')->sortable();
            $grid->column('level', '商业用户等级');
            if($recommenderInfo['has_reward']){
                $grid->column('reward', '中奖情况');
                $grid->disableActions();
            }else{
                $grid->actions(function (Grid\Displayers\Actions $actions) use ($recommenderInfo){
                    $actions->disableEdit();
                    $actions->disableView();
                    $actions->disableDelete();
                    $noteId = $actions->row->note_id;
                    if($recommenderInfo['end_time'] < time()){
                        if($recommenderInfo['reward_type'] == mGoodsRecommender::TYPE_POINT){
                            $actions->prepend(
                                '<select class="kj" id="'. $noteId .'" value="0">
                                <option value="0">未开奖</option>
                                <option value="1">一等奖</option>
                                <option value="2">二等奖</option>
                                <option value="3">三等奖</option>
                            </select>'
                            );
                        }else{
                            $actions->prepend(
                                '<select class="kj" id="'. $noteId .'" value="0">
                                <option value="0">未开奖</option>
                                <option value="1">一等奖</option>
                            </select>'
                            );
                        }
                    }

                });
                if($recommenderInfo['end_time'] < time()){
                    $grid->footer(function () {
                        $html = '<input class="btn btn-sm btn-success fa-trash" type="submit" id="tj_sub" value="提交" style="margin-right: 100px;width: 130px;height: 35px">';
                        return $html;
                    });
                }
            }
        });
        Admin::script($this->setScript($id));
        return $content
            ->header('内容列表')
            ->breadcrumb(
                ['text' => '']
            )
            ->body($listGrid);
    }

    public function save(Request $request){
        $params = $request->all();
        $goodsRecommender = mGoodsRecommender::getById($params['id']);
        $data = self::fomartReward($params['reward_data'],$params['id'],$goodsRecommender);
        if($data['insert_data']){
            GoodsRecommenderReward::insert($data['insert_data']);
            mGoodsRecommender::update(['has_reward' => 1],['id' => $params['id']]);
            if($goodsRecommender['reward_type'] == mGoodsRecommender::TYPE_POINT){
                self::addPoint($data['point_list'],$goodsRecommender['id']);
                self::sendSuccessMsg($data['point_list']);
            }
            self::sendfailMsg($data['failed_uids']);
            $status = true;
            $message = "操作成功";
        }else{
            $status = false;
            $message = "操作失败";
        }

        return response()->json(compact('status', 'message'));
    }

    private static function fomartReward($rewardStr,$id,$goodsRecommender)
    {
        $nowTime = time();
        $insertData = [];
        $tmpData = [];
        $rewardList = explode(',',$rewardStr);
        foreach($rewardList as $value){
            if($value){
                $tmpData[] = explode('-',$value);
            }
        }

        if($goodsRecommender['reward_type'] == mGoodsRecommender::TYPE_POINT){
            $pointInfo = json_decode($goodsRecommender['point_list'],1);
        }
        $rewardUid = [];
        $failedUid = [];
        foreach($tmpData as  $data){
            $uid = IdParse::getPhotoUid($data[0]);
            if($data[1] > 0){
                $insertData[] = [
                    'recommender_id' => $id,
                    'note_id' => $data[0],
                    'level' => $data[1],
                    'create_time' => $nowTime,
                    'status' => GoodsRecommenderReward::STATUS_NORMAL,
                ];
                $rewardUid[] = $uid;
                if($pointInfo){
                    $pointList[$uid]['obj_id'] = $data[0];
                    $pointList[$uid]['uid'] = IdParse::getPhotoUid($data[0]);
                    $pointList[$uid]['point'] = $pointInfo[$data[1]];
                }
            }else{
                $failedUid[] = $uid;
            }
        }
        $rewardUid = array_unique($rewardUid);
        $failedUid = array_unique($failedUid);
        foreach ($failedUid as $key => $uid){
            if(in_array($uid,$rewardUid)){
                unset($failedUid[$key]);
            }
        }
        $formatList['insert_data'] = $insertData;
        $formatList ['failed_uids'] = $failedUid;
        $formatList ['point_list'] = $pointList;
        return $formatList;
    }

    private static function sendSuccessMsg($pointList = array())
    {
        foreach ($pointList as $pointInfo){
            Queue::insertQueue('queue/Sysmsg/Send', [
                'msgCode' => 739,
                'to_uid' => $pointInfo['uid'],
                'msgParams' => [
                    'num' => $pointInfo['point'],
                ],
            ], Queue::QUEUE_DORAEMON);
        }
    }

    private static function sendfailMsg($uids = array())
    {
        foreach ($uids as $uid){
            Queue::insertQueue('queue/Sysmsg/Send', [
                'msgCode' => 740,
                'to_uid' => $uid,
                'msgParams' => [],
            ], Queue::QUEUE_DORAEMON);
        }
    }

    private static function addPoint($pointList  = array(),$id)
    {
        $remarks = array(
            'recommender_id' => $id,
        );
        foreach ($pointList as $pointInfo){
            \Doraemon\amqp\CommunityQueue::insertQueue(PointConfig::MQ_QUEUE_URL, [
                'event_name' => PointConfig::POINT_TYPE_RECOMMENDER_REWARD,
                'obj_id' => $pointInfo['obj_id'],
                'point' => $pointInfo['point'],
                'uid' => $pointInfo['uid'],
                'remarks' => json_encode($remarks),
                'type' => PointConfig::POINT_AWARD
            ], \Doraemon\amqp\CommunityQueue::QUEUE_COMMUNITY);
        }

    }

    public function setScript($id)
    {
        $js = 'var id = '.$id .';';

        $js .=  <<<SCRIPT

        $('#tj_sub').unbind('click').click(function() {
            layer.confirm('确定提交么？', {
                btn: ['确定', '取消']
            }, function (index) {
                var x = $(".kj")
                var y = $(".kj option:selected")
                var arr = []
                var selectArr = [];
                
                var reward_data = '';
                for (var i = x.length - 1; i >= 0; i--) {
                    reward_data += x.eq(i).attr('id') + '-' + y.eq(i).val() + ',';
                }
                var url = '/admin/communityMcn/joinList/save'
                var params = {
                    reward_data:reward_data,
                    id:id
                };
                $.post(url,params,function (result){
                    if (result.status == 1){
                        layer.msg(result.message);
                        window.location.replace('/admin/communityMcn/joinList/'+id+'/list'); 
                    }else{
                        layer.msg(result.message);
                    }
                });
                layer.msg(result.message);
                console.log(reward_data);
            });
    
		});
SCRIPT;
        return $js;
    }
}